# Oracle.ManagedDataAccess.Core 升级脚本
# 解决Oracle客户端依赖问题的快速方案

Write-Host "=== Oracle.ManagedDataAccess.Core 升级脚本 ===" -ForegroundColor Green
Write-Host "此脚本将升级项目到纯托管Oracle驱动，无需Oracle客户端" -ForegroundColor Yellow
Write-Host ""

# 检查当前目录
$currentDir = Get-Location
Write-Host "当前目录: $currentDir" -ForegroundColor Cyan

# 查找项目文件
$projectFile = Get-ChildItem -Name "*.csproj" | Select-Object -First 1
if (-not $projectFile) {
    Write-Host "错误: 未找到.csproj文件" -ForegroundColor Red
    exit 1
}

Write-Host "找到项目文件: $projectFile" -ForegroundColor Green

# 备份项目文件
$backupFile = "$projectFile.backup.$(Get-Date -Format 'yyyyMMdd-HHmmss')"
Copy-Item $projectFile $backupFile
Write-Host "已备份项目文件: $backupFile" -ForegroundColor Yellow

# 读取项目文件内容
$projectContent = Get-Content $projectFile -Raw

# 检查当前Oracle包
Write-Host "
=== 检查当前Oracle NuGet包 ===" -ForegroundColor Cyan
if ($projectContent -match 'Oracle\.ManagedDataAccess') {
    Write-Host "发现现有Oracle.ManagedDataAccess包" -ForegroundColor Yellow
    
    # 提取版本信息
    if ($projectContent -match 'Oracle\.ManagedDataAccess.*Version="([^"]+)"') {
        $currentVersion = $matches[1]
        Write-Host "当前版本: $currentVersion" -ForegroundColor White
    }
} else {
    Write-Host "未发现Oracle.ManagedDataAccess包" -ForegroundColor Yellow
}

# 移除旧的Oracle包
Write-Host "
=== 移除旧的Oracle包 ===" -ForegroundColor Cyan
try {
    dotnet remove package Oracle.ManagedDataAccess 2>$null
    Write-Host "已移除 Oracle.ManagedDataAccess" -ForegroundColor Green
} catch {
    Write-Host "Oracle.ManagedDataAccess 包不存在或已移除" -ForegroundColor Yellow
}

# 添加新的Core包
Write-Host "
=== 添加 Oracle.ManagedDataAccess.Core ===" -ForegroundColor Cyan
try {
    $addResult = dotnet add package Oracle.ManagedDataAccess.Core --version 23.6.0
    if ($LASTEXITCODE -eq 0) {
        Write-Host "成功添加 Oracle.ManagedDataAccess.Core 23.6.0" -ForegroundColor Green
    } else {
        throw "添加包失败"
    }
} catch {
    Write-Host "错误: 添加Oracle.ManagedDataAccess.Core失败" -ForegroundColor Red
    Write-Host "错误信息: $_" -ForegroundColor Red
    exit 1
}

# 检查appsettings.json并优化连接字符串
Write-Host "
=== 优化连接字符串配置 ===" -ForegroundColor Cyan
$appsettingsFile = "appsettings.json"
if (Test-Path $appsettingsFile) {
    Write-Host "找到 $appsettingsFile" -ForegroundColor Green
    
    # 备份appsettings.json
    $appsettingsBackup = "$appsettingsFile.backup.$(Get-Date -Format 'yyyyMMdd-HHmmss')"
    Copy-Item $appsettingsFile $appsettingsBackup
    Write-Host "已备份: $appsettingsBackup" -ForegroundColor Yellow
    
    # 读取并解析JSON
    try {
        $appsettingsContent = Get-Content $appsettingsFile -Raw | ConvertFrom-Json
        
        # 检查连接字符串
        if ($appsettingsContent.ConnectionStrings) {
            Write-Host "发现连接字符串配置" -ForegroundColor Green
            
            # 优化Oracle连接字符串
            foreach ($connName in $appsettingsContent.ConnectionStrings.PSObject.Properties.Name) {
                $connString = $appsettingsContent.ConnectionStrings.$connName
                
                if ($connString -match "Data Source.*Oracle|User Id.*Oracle" -or $connString -match "oracle|ORACLE") {
                    Write-Host "优化连接字符串: $connName" -ForegroundColor Cyan
                    
                    # 确保包含关键参数
                    $optimizedParams = @(
                        "Connection Timeout=90",
                        "Pooling=true",
                        "Min Pool Size=5",
                        "Max Pool Size=100",
                        "Connection Lifetime=300",
                        "Validate Connection=true",
                        "Self Tuning=true"
                    )
                    
                    $baseConnString = $connString
                    foreach ($param in $optimizedParams) {
                        $paramName = $param.Split('=')[0]
                        if ($baseConnString -notmatch [regex]::Escape($paramName)) {
                            if ($baseConnString.EndsWith(';')) {
                                $baseConnString += $param + ";"
                            } else {
                                $baseConnString += ";" + $param + ";"
                            }
                        }
                    }
                    
                    $appsettingsContent.ConnectionStrings.$connName = $baseConnString
                    Write-Host "已优化连接字符串参数" -ForegroundColor Green
                }
            }
            
            # 保存更新的配置
            $appsettingsContent | ConvertTo-Json -Depth 10 | Set-Content $appsettingsFile -Encoding UTF8
            Write-Host "已更新 $appsettingsFile" -ForegroundColor Green
        }
    } catch {
        Write-Host "警告: 无法解析或更新appsettings.json: $_" -ForegroundColor Yellow
    }
} else {
    Write-Host "未找到 appsettings.json" -ForegroundColor Yellow
}

# 创建连接测试工具
Write-Host "
=== 创建连接测试工具 ===" -ForegroundColor Cyan
$testToolContent = @'
using Oracle.ManagedDataAccess.Client;
using Microsoft.Extensions.Configuration;
using System;
using System.Threading.Tasks;

namespace Lzfy_His_Service
{
    /// <summary>
    /// Oracle.ManagedDataAccess.Core 连接测试工具
    /// 验证纯托管驱动的连接性能
    /// </summary>
    public class ManagedOracleConnectionTest
    {
        private readonly IConfiguration _configuration;
        
        public ManagedOracleConnectionTest(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        
        /// <summary>
        /// 测试Oracle连接（纯托管驱动）
        /// </summary>
        public async Task<bool> TestConnectionAsync(string connectionName = "OracleConnection")
        {
            try
            {
                var connectionString = _configuration.GetConnectionString(connectionName);
                if (string.IsNullOrEmpty(connectionString))
                {
                    Console.WriteLine($"错误: 未找到连接字符串 '{connectionName}'");
                    return false;
                }
                
                Console.WriteLine("=== Oracle.ManagedDataAccess.Core 连接测试 ===");
                Console.WriteLine($"连接字符串: {MaskConnectionString(connectionString)}");
                Console.WriteLine($"驱动类型: 纯托管驱动 (无需Oracle客户端)");
                
                var startTime = DateTime.Now;
                
                using (var connection = new OracleConnection(connectionString))
                {
                    Console.WriteLine("正在连接Oracle数据库...");
                    await connection.OpenAsync();
                    
                    var connectTime = DateTime.Now - startTime;
                    Console.WriteLine($"连接成功! 耗时: {connectTime.TotalMilliseconds:F2}ms");
                    
                    // 测试查询
                    using (var command = new OracleCommand("SELECT SYSDATE FROM DUAL", connection))
                    {
                        var queryStart = DateTime.Now;
                        var result = await command.ExecuteScalarAsync();
                        var queryTime = DateTime.Now - queryStart;
                        
                        Console.WriteLine($"查询测试成功! 服务器时间: {result}");
                        Console.WriteLine($"查询耗时: {queryTime.TotalMilliseconds:F2}ms");
                    }
                    
                    // 连接池信息
                    Console.WriteLine($"连接状态: {connection.State}");
                    Console.WriteLine($"Oracle版本: {connection.ServerVersion}");
                    Console.WriteLine($"数据库名称: {connection.DatabaseName}");
                    
                    Console.WriteLine("=== 连接测试完成 ===");
                    return true;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"连接失败: {ex.Message}");
                Console.WriteLine($"错误类型: {ex.GetType().Name}");
                
                if (ex.InnerException != null)
                {
                    Console.WriteLine($"内部错误: {ex.InnerException.Message}");
                }
                
                return false;
            }
        }
        
        /// <summary>
        /// 性能基准测试
        /// </summary>
        public async Task<TimeSpan> BenchmarkConnectionAsync(string connectionName = "OracleConnection", int iterations = 10)
        {
            var connectionString = _configuration.GetConnectionString(connectionName);
            var totalTime = TimeSpan.Zero;
            var successCount = 0;
            
            Console.WriteLine($"\n=== 性能基准测试 ({iterations}次连接) ===");
            
            for (int i = 0; i < iterations; i++)
            {
                try
                {
                    var startTime = DateTime.Now;
                    
                    using (var connection = new OracleConnection(connectionString))
                    {
                        await connection.OpenAsync();
                        
                        using (var command = new OracleCommand("SELECT 1 FROM DUAL", connection))
                        {
                            await command.ExecuteScalarAsync();
                        }
                    }
                    
                    var elapsed = DateTime.Now - startTime;
                    totalTime = totalTime.Add(elapsed);
                    successCount++;
                    
                    Console.Write($".");
                }
                catch (Exception ex)
                {
                    Console.Write($"X");
                    Console.WriteLine($"\n第{i+1}次连接失败: {ex.Message}");
                }
            }
            
            Console.WriteLine();
            Console.WriteLine($"成功连接: {successCount}/{iterations}");
            Console.WriteLine($"平均耗时: {totalTime.TotalMilliseconds / successCount:F2}ms");
            Console.WriteLine($"总耗时: {totalTime.TotalMilliseconds:F2}ms");
            
            return totalTime;
        }
        
        private string MaskConnectionString(string connectionString)
        {
            return System.Text.RegularExpressions.Regex.Replace(
                connectionString, 
                @"(Password|Pwd)\s*=\s*[^;]+", 
                "Password=***", 
                System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        }
    }
}
'@

$testToolFile = "ManagedOracleConnectionTest.cs"
Set-Content $testToolFile $testToolContent -Encoding UTF8
Write-Host "已创建: $testToolFile" -ForegroundColor Green

# 编译项目
Write-Host "
=== 编译项目 ===" -ForegroundColor Cyan
try {
    $buildResult = dotnet build --configuration Release
    if ($LASTEXITCODE -eq 0) {
        Write-Host "项目编译成功!" -ForegroundColor Green
    } else {
        Write-Host "警告: 项目编译可能有问题，请检查" -ForegroundColor Yellow
    }
} catch {
    Write-Host "编译过程中出现错误: $_" -ForegroundColor Yellow
}

# 显示升级总结
Write-Host "
" -ForegroundColor White
Write-Host "=== 升级完成总结 ===" -ForegroundColor Green
Write-Host "✓ 已升级到 Oracle.ManagedDataAccess.Core 23.6.0" -ForegroundColor Green
Write-Host "✓ 纯托管驱动，无需Oracle客户端" -ForegroundColor Green
Write-Host "✓ 已优化连接字符串参数" -ForegroundColor Green
Write-Host "✓ 已创建连接测试工具" -ForegroundColor Green
Write-Host "✓ 项目编译完成" -ForegroundColor Green

Write-Host "
=== 关键优势 ===" -ForegroundColor Cyan
Write-Host "• 无需安装Oracle客户端" -ForegroundColor White
Write-Host "• 无需配置环境变量" -ForegroundColor White
Write-Host "• 支持32位和64位应用" -ForegroundColor White
Write-Host "• 简化DMZ环境部署" -ForegroundColor White
Write-Host "• 消除版本冲突问题" -ForegroundColor White

Write-Host "
=== 后续步骤 ===" -ForegroundColor Yellow
Write-Host "1. 测试应用程序功能" -ForegroundColor White
Write-Host "2. 运行连接测试: ManagedOracleConnectionTest" -ForegroundColor White
Write-Host "3. 部署到测试环境验证" -ForegroundColor White
Write-Host "4. 监控性能和稳定性" -ForegroundColor White
Write-Host "5. 部署到生产环境" -ForegroundColor White

Write-Host "
=== 备份文件 ===" -ForegroundColor Cyan
Write-Host "项目文件备份: $backupFile" -ForegroundColor White
if (Test-Path $appsettingsBackup) {
    Write-Host "配置文件备份: $appsettingsBackup" -ForegroundColor White
}

Write-Host "
升级完成! 现在您的应用程序使用纯托管Oracle驱动，无需Oracle客户端依赖。" -ForegroundColor Green
Write-Host "如有问题，请参考: Oracle连接不依赖客户端的NuGet解决方案.md" -ForegroundColor Yellow